<?php
namespace Api\Model\Amazon;

class ReportModel extends CommonModel {

    protected $logModel = NULL;

    public function __construct() {
        define ('DATE_FORMAT', 'Y-m-d H:i:s');
        $this->logModel = D('Api/Amazon/Log','Model');
        $this->vendorApi('MarketplaceWebService.Client');
        $this->vendorApi('MarketplaceWebService.Exception');
    }

    /**
     * @param $account
     * @param $options
     * @return array|bool
     */
    public function requestReport ($account, $options) {
        $this->vendorApi('MarketplaceWebService.Model.RequestReportRequest');
        $this->vendorApi('MarketplaceWebService.Model.IdList');
        $request = new \MarketplaceWebService_Model_RequestReportRequest($options);
        $request->setMerchant($account['merchant_id']);
        $request->setMarketplace($account['marketplace_id']);
        if($options['ReportType'] == '_GET_FBA_FULFILLMENT_CURRENT_INVENTORY_DATA_' || $options['ReportType'] == '_GET_MERCHANT_LISTINGS_DATA_'){
            $arr['Id'] = $account['marketplace_id'];
            $request->setMarketplaceIdList($arr);
        }
        $service = $this->getService($account);
        try {
            $response = $service->requestReport($request);

            $this->logModel->apiLog('RequestReport', $account, $options, $request, $response);

            $reportInfo = array();
            if ($response->isSetRequestReportResult()) {
                $requestReportResult = $response->getRequestReportResult();

                if ($requestReportResult->isSetReportRequestInfo()) {

                    $reportRequestInfo = $requestReportResult->getReportRequestInfo();
                    if ($reportRequestInfo->isSetReportRequestId()) {
                        $reportInfo['ReportRequestId'] = $reportRequestInfo->getReportRequestId();
                    }

                    if ($reportRequestInfo->isSetReportType()) {
                        $reportInfo['ReportType'] = $reportRequestInfo->getReportType();
                    }

                    if ($reportRequestInfo->isSetStartDate()) {
                        $reportInfo['StartDate'] = $reportRequestInfo->getStartDate()->format(DATE_FORMAT);
                    }

                    if ($reportRequestInfo->isSetEndDate()) {
                        $reportInfo['EndDate'] = $reportRequestInfo->getEndDate()->format(DATE_FORMAT);
                    }

                    if ($reportRequestInfo->isSetSubmittedDate()) {
                        $reportInfo['SubmittedDate'] = $reportRequestInfo->getSubmittedDate()->format(DATE_FORMAT);
                    }

                    if ($reportRequestInfo->isSetReportProcessingStatus()) {
                        $reportInfo['ReportProcessingStatus'] = $reportRequestInfo->getReportProcessingStatus();
                    }
                }
            }

            if ($response->isSetResponseMetadata()) {
                $responseMetadata = $response->getResponseMetadata();
                if ($responseMetadata->isSetRequestId()) {
                    $reportInfo['RequestId'] = $responseMetadata->getRequestId();
                }
            }

            $reportInfo['ResponseHeaderMetadata'] = $response->getResponseHeaderMetadata();
            !empty($service->curlError) && $this->error = $service->curlError;
            return $reportInfo;
        } catch (\MarketplaceWebService_Exception $ex) {
            $this->logModel->apiErrorLog('RequestReport', $account, $options, $request, $ex);
            $this->error = $ex->getMessage();
            !empty($service->curlError) && $this->error .= $service->curlError;
            return FALSE;
        }
    }

    /**
     * @param $account
     * @param $options
     * @return array|bool
     * 获取报告请求列表以及每个报告请求的状态和编号
     */
    public function getReportRequestList ($account, $options) {
        $this->vendorApi('MarketplaceWebService.Model.GetReportRequestListRequest');
        $this->vendorApi('MarketplaceWebService.Model.GetReportRequestListByNextTokenRequest');

        $request = new \MarketplaceWebService_Model_GetReportRequestListRequest($options);
        $request->setMerchant($account['merchant_id']);
        if($options['ReportType'] == '_GET_FBA_FULFILLMENT_CURRENT_INVENTORY_DATA_' || $options['ReportType'] == '_GET_MERCHANT_LISTINGS_DATA_'){
            $request->setMarketplace($account['marketplace_id']);
        }
        $service = $this->getService($account);

        $results = array();
        try {
            $response = $service->getReportRequestList($request);

            $this->logModel->apiLog('GetReportRequestList', $account, $options, $request, $response);

            if ($response->isSetGetReportRequestListResult()) {
                $getReportRequestListResult = $response->getGetReportRequestListResult();
                $results = $this->reportRequestListFormat($getReportRequestListResult);
                while($getReportRequestListResult->isSetHasNext() && $getReportRequestListResult->getHasNext()) {
                    $request = new \MarketplaceWebService_Model_GetReportRequestListByNextTokenRequest();
                    $request->setNextToken($getReportRequestListResult->getNextToken());
                    $request->setMerchant($account['merchant_id']);

                    $response = $service->getReportRequestListByNextToken($request);

                    $this->logModel->apiLog('GetReportRequestListByNextToken', $account, $options, $request, $response);

                    if ($response->isSetGetReportRequestListByNextTokenResult()) {
                        $getReportRequestListResult = $response->getGetReportRequestListByNextTokenResult();
                        $results = array_merge($results, $this->reportRequestListFormat($getReportRequestListResult));
                    } else {
                        break;
                    }
                }
            }

            return $results;
        } catch (\MarketplaceWebService_Exception $ex) {
            $this->logModel->apiErrorLog('GetReportRequestList', $account, $options, $request, $ex);
            $this->error = $ex->getMessage();
            !empty($service->curlError) && $this->error .= $service->curlError;
            return FALSE;
        }
    }

    /**
     * @param $account
     * @param array $options
     * @return array|bool
     *
     */
    public function getReportList($account, $options = array()) {
        $this->vendorApi('MarketplaceWebService.Model.GetReportListRequest');
        $this->vendorApi('MarketplaceWebService.Model.GetReportListByNextTokenRequest');

        $service = $this->getService($account);

        $request = new \MarketplaceWebService_Model_GetReportListRequest($options);
        $request->setMerchant($account['merchant_id']);
        if($options['ReportType'] == '_GET_FBA_FULFILLMENT_CURRENT_INVENTORY_DATA_'|| $options['ReportType'] == '_GET_MERCHANT_LISTINGS_DATA_'){
            $request->setMarketplace($account['marketplace_id']);
        }
        $reportLists = array();

        try{
            $response = $service->getReportList($request);
            $this->logModel->apiLog('GetReportList', $account, $options, $request, $response);

            if($response->isSetGetReportListResult()){

                $getReportListResult = $response->getGetReportListResult();
                $reportLists = $this->getReportListFormat($getReportListResult);

                while($getReportListResult->isSetHasNext() && $getReportListResult->getHasNext()) {
                    $request = new \MarketplaceWebService_Model_GetReportListByNextTokenRequest();
                    $request->setMerchant($account['merchant_id']);
                    $request->setNextToken($getReportListResult->getNextToken());

                    $response = $service->getReportListByNextToken($request);
                    $this->logModel->apiLog('GetReportListByNextToken', $account, $options, $request, $response);

                    if ($response->isSetGetReportListByNextTokenResult()) {
                        $getReportListResult = $response->getGetReportListByNextTokenResult();

                        $reportLists = array_merge($reportLists, $this->getReportListFormat($getReportListResult));
                    }
                }
            }

            return $reportLists;
        } catch(\MarketplaceWebService_Exception $ex) {
            $this->logModel->apiErrorLog('GetReportList',$account,$options,$request,$ex);
            $this->error = $ex->getMessage();
            !empty($service->curlError) && $this->error .= $service->curlError;
            return FALSE;
        }
    }

    /**
     * 根据报表ID获取报告文件
     * @param $account
     * @param $ReportId
     * @return array|bool
     * 返回在过去 90 天内所创建的报告列表或者某个报表ID
     */
    public function getReport($account, $ReportId) {
        $this->vendorApi('MarketplaceWebService.Model.GetReportRequest');

        $service = $this->getService($account);

        $request = new \MarketplaceWebService_Model_GetReportRequest();
        $request->setMerchant($account['merchant_id']);
        $request->setReport(@fopen('php://memory','rw+'));
        $request->setReportId($ReportId);

        try{
            $response = $service->getReport($request);
            $this->logModel->apiLog(
                'GetReport',
                $account,
                array(
                    'Merchant'=>$account['merchant_id'],
                    'ReportId'=>$ReportId,
                    'account_id'=>$account['id'],
                ),
                $request,
                $response
            );
            if($response->isSetGetReportResult()){
                $result = $response->getGetReportResult();

                $report = array();
                $report['ContentMd5'] = $result->getContentMd5();
                $report['Data'] = stream_get_contents($request->getReport());

                return $report;
            }

            $this->error = '没有获取到相关报告数据 ';
            !empty($service->curlError) && $this->error .= $service->curlError;
            return FALSE;

        }catch(\MarketplaceWebService_Exception $ex){
            $this->logModel->apiErrorLog('GetReport',$account,$ReportId,$request,$ex);
            $this->error = $ex->getMessage();
            !empty($service->curlError) && $this->error .= $service->curlError;
            return FALSE;
        }
    }

    private function getReportListFormat ($getReportListResult) {
        $lists = array();
        $reportInfoList = $getReportListResult->getReportInfoList();
        foreach ($reportInfoList as $reportInfo) {
            $list = array();

            if ($reportInfo->isSetReportId()) {
                $list['ReportId'] = $reportInfo->getReportId();
            }
            if ($reportInfo->isSetReportType()) {
                $list['ReportType'] = $reportInfo->getReportType();
            }
            if ($reportInfo->isSetReportRequestId()) {
                $list['ReportRequestId'] = $reportInfo->getReportRequestId();
            }
            if ($reportInfo->isSetAvailableDate()) {
                $list['AvailableDate'] = $reportInfo->getAvailableDate()->format(DATE_FORMAT);
            }
            if ($reportInfo->isSetAcknowledged()) {
                $list['Acknowledged'] = $reportInfo->getAcknowledged();
            }
            if ($reportInfo->isSetAcknowledgedDate()) {
                $list['AcknowledgedDate'] = $reportInfo->getAcknowledgedDate()->format(DATE_FORMAT);
            }

            $lists[] = $list;
        }

        return $lists;
    }

    /*降批量获取某个账号下的所有报表计划的状态获取下来*/
    public function reportRequestListFormat ($getReportRequestListResult) {
        $resultPiece = array();
        $reportRequestInfoList = $getReportRequestListResult->getReportRequestInfoList();
        foreach ($reportRequestInfoList as $reportRequestInfo) {
            $resultInfo = array();
            if ($reportRequestInfo->isSetReportRequestId()) {
                $resultInfo['ReportRequestId'] = $reportRequestInfo->getReportRequestId();
            }
            if ($reportRequestInfo->isSetReportType()) {
                $resultInfo['ReportType'] = $reportRequestInfo->getReportType();
            }
            if ($reportRequestInfo->isSetStartDate()) {
                $resultInfo['StartDate'] = $reportRequestInfo->getStartDate()->format(DATE_FORMAT);
            }
            if ($reportRequestInfo->isSetEndDate()) {
                $resultInfo['EndDate'] = $reportRequestInfo->getEndDate()->format(DATE_FORMAT);
            }
            if ($reportRequestInfo->isSetScheduled()) {
                $resultInfo['Scheduled'] = $reportRequestInfo->getScheduled();
            }
            if ($reportRequestInfo->isSetSubmittedDate()) {
                $resultInfo['SubmittedDate'] = $reportRequestInfo->getSubmittedDate()->format(DATE_FORMAT);
            }
            if ($reportRequestInfo->isSetReportProcessingStatus()) {
                $resultInfo['ReportProcessingStatus'] = $reportRequestInfo->getReportProcessingStatus();
            }
            // add start
            if ($reportRequestInfo->isSetGeneratedReportId()) {
                $resultInfo['GeneratedReportId'] = $reportRequestInfo->getGeneratedReportId();
            }
            if ($reportRequestInfo->isSetStartedProcessingDate()) {
                $resultInfo['StartedProcessingDate'] = $reportRequestInfo->getStartedProcessingDate()->format(DATE_FORMAT);
            }
            if ($reportRequestInfo->isSetCompletedDate()) {
                $resultInfo['CompletedDate'] = $reportRequestInfo->getCompletedDate()->format(DATE_FORMAT);
            }

            $resultPiece[] = $resultInfo;
        }

        return $resultPiece;
    }

    /**
     * @param $account
     * @return bool|\MarketplaceWebService_Client
     * 根据账号数组信息获取对应账号站点服务客户端
     */
    private function getService($account){
        if(empty($account) || !is_array($account)) return false;
        $config = array(
            'ServiceURL'    => $account['service_url_report'],
            'ProxyHost'     => NULL,
            'ProxyPort'     => -1,
            'ProxyUsername' => null,
            'ProxyPassword' => null,
            'MaxErrorRetry' => 3,
        );

        return new \MarketplaceWebService_Client($account['access_key_id'],$account['secret_key'],$config,'yks','1.0');
    }
}